package com.manager.commons.utils;

//                   _ooOoo_    
//                  o8888888o    
//                  88" . "88    
//                  (| -_- |)    
//                   O\ = /O    
//               ____/'---'\____    
//              /. '\\| : |//' .\    
//             // \\||| : |||// \\   
//            // _|||||-:-|||||_ \\    
//           // | | \\\ - /// | | \\
//           || |_| ''\---/'' |_| || 
//            \ .-\___/'-'\___/-. /    
//          ___\. .' /--.--\ '. ./___    
//        .""'< `.___\_<|>_/___.' >'"".    
//       | |: `- \`.|'\ _ /'|.`/ -` :| |    
//        \ \ `-. \_ __\ /__ _/ .-` / /    
//======'-.___`-.___\_______/___.-`___.-'======    
//                   '=---='    
//.................................................    
//写一哈代码，你就青叫唤；信龟儿设计，你逗是傻逼。
//永无Bug，啷个可能！求佛主保佑也没球用！

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;

import com.manager.commons.log.LogFactory;

/**
 * HttpUtil(请求)
 * @author H
 * @version V1.0
 */
public class HttpUtil {

	private static final Logger logger = LogFactory.getLogger(HttpUtil.class);

	/**
	 * 执行一个HTTP GET请求，返回请求响应的HTML
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doGet(String url, String params) {
		return doGet(url, params, "utf-8", false);
	}

	/**
	 * 执行一个HTTP GET请求，返回请求响应的HTML
	 * @param url     请求的URL地址
	 * @param params  请求的查询参数,可以为null
	 * @param charset 字符集
	 * @param pretty  是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doGet(String url, String params, String charset, boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (params != null && !params.equals("")) {
				method.setQueryString(URIUtil.encodeQuery(params));
			}
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty) {
						response.append(line).append(System.getProperty("line.separator"));
					} else {
						response.append(line);
					}
				}
				reader.close();
			} else {
				logger.info("status code:" + method.getStatusCode() + "-status text:" + method.getStatusText()
						+ "-status line:" + method.getStatusLine());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			method.releaseConnection();
		}
		return response.toString();
	}

	/**
	 * post
	 * @param url
	 * @param pars
	 * @param data
	 * @return
	 */
	public static String postMsg(String url, String pars, String data) {
		String result = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
					.setConnectionRequestTimeout(5000).build();
			httpPost.setConfig(requestConfig);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair(pars, data));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			CloseableHttpResponse response = null;
			try {
				response = httpclient.execute(httpPost);
				int statusCode = response.getStatusLine().getStatusCode();
				if (statusCode == HttpStatus.SC_OK) {
					HttpEntity entity = response.getEntity();
					result = EntityUtils.toString(entity);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return result;
	}

	/**
	 * 执行一个HTTP POST请求，返回请求响应的HTML
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map<String, Object> params) {
		return doPost(url, params, "utf-8", false);
	}

	/**
	 * 执行一个HTTP POST请求，返回请求响应的HTML
	 * @param url     请求的URL地址
	 * @param params  请求的查询参数,可以为null
	 * @param charset 字符集
	 * @param pretty  是否美化
	 */
	public static String doPost(String url, Map<String, Object> params, String charset, boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new PostMethod(url);
		if (params != null) {
			HttpMethodParams p = new HttpMethodParams();
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				p.setParameter(entry.getKey(), entry.getValue());
			}
			method.setParams(p);
		}
		try {
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty) {
						response.append(line).append(System.getProperty("line.separator"));
					} else {
						response.append(line);
					}
				}
				reader.close();
			} else {
				logger.info(method.getStatusCode() + ":" + method.getStatusText());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			method.releaseConnection();
		}
		return response.toString();
	}

	/**
	 * post Json
	 * @param url
	 * @param json
	 * @return
	 * @throws Exception
	 */
	public static String postJson(String url, String json) {
		String result = "";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		try {
			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			httpPost.setEntity(new StringEntity(json, "UTF-8"));
			CloseableHttpResponse response = httpClient.execute(httpPost);
			result = EntityUtils.toString(response.getEntity(), "UTF-8");
			response.close();
			httpClient.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				if (null != httpClient) {
					httpClient.close();
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		return result;
	}
}